package cn.edu.scujj.view;

import cn.edu.scujj.bean.BookType;
import cn.edu.scujj.dao.TongjiDao;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.List;
import java.util.Vector;

public class TongjiUI extends JFrame {
    private JScrollPane jScrollPane = new JScrollPane();
    private AbstractTableModel tableModel;
    private Vector<Vector<Object>> vector = new Vector<>();

    private JTextField textField1 = new JTextField(10);
    private JTextField textField2 = new JTextField(10);
    private JTextField totalCountField = new JTextField(10);

    public TongjiUI() {
        setTitle("图书类别统计");
        setBounds(100, 100, 800, 600);
        setLayout(new BorderLayout());
        JPanel panelCenter = new JPanel();
        JPanel panelDown = new JPanel();
        JPanel panelUP= new JPanel();
        panelUP.add(jScrollPane);

        createTable();

        add(panelUP,BorderLayout.NORTH);
        add(panelCenter,BorderLayout.CENTER);
        add(panelDown,BorderLayout.SOUTH);

        totalCountField.setEditable(false);
        panelCenter.add(new JLabel("类别总数为："));
        panelCenter.add(totalCountField);


        select();

    }

    private void createTable() {
        String[] columnNames = {"图书类别ID","图书类别名称"};
        JTable table = new JTable();
        jScrollPane.setViewportView(table);
        tableModel = new AbstractTableModel() {
            @Override
            public int getRowCount() {
                return vector.size();
            }

            @Override
            public int getColumnCount() {
                return columnNames.length;
            }

            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                Object value = ((Vector)vector.get(rowIndex)).get(columnIndex);
                if (value instanceof Integer) {
                    return value;
                } else if (value instanceof String && columnIndex == 0) {
                    try {
                        return Integer.parseInt((String)value);
                    } catch (NumberFormatException e) {
                        return 0;
                    }
                }
                return value;
            }

            @Override
            public String getColumnName(int column) {
                return columnNames[column];
            }
        };
        table.setModel(tableModel);
    }
    void select() {
        vector.clear();
        TongjiDao dao = new TongjiDao();
        List<BookType> list = dao.findAll();
        for (BookType bookType : list) {
            Vector v = new Vector();
            v.add(bookType.getTypeId());
            v.add(bookType.getTypeName());
            vector.add(v);
        }
        tableModel.fireTableDataChanged();
        totalCountField.setText(String.valueOf(list.size()));
    }
    public static void main(String[] args) {
        new TongjiUI().setVisible(true);
    }

}
